package com.onlyxiahui.framework.json.validator.impl;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.framework.json.validator.Validator;
import com.onlyxiahui.framework.json.validator.ValidatorContext;
import com.onlyxiahui.framework.json.validator.ValidatorData;
import com.onlyxiahui.framework.json.validator.ValidatorResult;
import com.onlyxiahui.framework.json.validator.error.ErrorInfoEnum;
import com.onlyxiahui.framework.json.validator.util.RegexValidatorUtil;

/**
 * 
 * Date 2018-12-26 17:23:34<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class JsonMinSizeValidator implements Validator<JSONObject, Object> {

	@Override
	public String getKey() {
		return "minSize";
	}

	@Override
	public boolean check(Object judge) {
		return null != judge && RegexValidatorUtil.isInteger(judge.toString());
	}

	@Override
	public ValidatorResult valid(ValidatorContext validatorContext, ValidatorData<JSONObject, Object> vd) {
		// JSONObject data = vd.getData();
		Object attribute = vd.getAttribute();
		Object judge = vd.getJudge();
		String code = vd.getCode();
		String message = vd.getMessage();

		ValidatorResult vr = null;
		boolean mark = true;
		Integer maxSize = 0;
		if (null != attribute && null != judge) {

			int size = 0;
			boolean isCollection = attribute instanceof Collection;
			boolean isList = attribute instanceof List;
			boolean isSet = attribute instanceof Set;
			boolean isArray = attribute.getClass().isArray();

			boolean ck = isCollection || isList || isSet || isArray;

			if (isCollection) {
				size = ((Collection<?>) attribute).size();
			}
			if (isList) {
				size = ((List<?>) attribute).size();
			}
			if (isSet) {
				size = ((Set<?>) attribute).size();
			}
			if (isArray) {
				size = Array.getLength(attribute);
			}

			String judgeText = judge.toString();

			boolean isJudgeNumber = RegexValidatorUtil.isInteger(judgeText);

			if (isJudgeNumber && ck) {
				maxSize = Integer.valueOf(judgeText);
				mark = (maxSize.compareTo(size) <= 0);
			}
		}
		if (!mark) {
			vr = new ValidatorResult();
			vr.setErrorCode(code == null ? this.getCode() : code);
			vr.setMessage(message == null ? this.getMessage(maxSize) : message);
			vr.setExtend(vd.getExtend());
		}
		return vr;
	}

	public String getMessage(Integer maxBigDecimal) {
		StringBuilder message = new StringBuilder("数量不能小于");
		if (null != maxBigDecimal) {
			message.append(maxBigDecimal.toString());
		}
		message.append("！");
		return message.toString();
	}

	public String getCode() {
		return ErrorInfoEnum.RANGE_ERROR.code();
	}
}
